﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ASC.Models;

namespace ASC.Controllers
{
    public class TreeController : BaseController
    {
        //
        // GET: /Tree/

        public ActionResult Index()
        {
            var channels = this.db.Channels
                .Select(x => new TreeNodeModel() { 
                    Id = x.Channel_Id, 
                    Name = x.Name, 
                    Description = x.Description, 
                    Type = (int)TreeNodeType.Channel,
                    Used = x.Used
                })
                .ToList();

            var moduls = this.db.Modules
                .Select(x => new TreeNodeModel() { 
                    Id = x.Module_Id, 
                    Name = x.Name, 
                    Description = x.Description, 
                    Type = (int)TreeNodeType.Module,
                    Used = x.Used
                }) 
                .ToList();

            moduls.ForEach(x => {
                if (x.Used)
                {
                    var childChannels = (from mch in this.db.Module_Channel
                                        join ch in this.db.Channels on mch.Channel_Id equals ch.Channel_Id
                                        where mch.Module_Id == x.Id
                                        select ch)
                                        .ToList()
                                        .Select(c => new TreeNodeModel() { 
                                            Id = c.Channel_Id, 
                                            Name = c.Name, 
                                            Description = c.Description, 
                                            Type = (int)TreeNodeType.Channel,
                                            Used = c.Used
                                        });

                    x.ChildChannels = childChannels.ToList();

                }
            });

            var treeNodeModelList = channels.Union(moduls);

            return View(treeNodeModelList);
        }

    }
}
